package cn.ekuma.odbo.mobile.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import cn.ekuma.odbo.mobile.base.I_BrowsableEditableData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * A ViewModel which is also Coroutine aware.
 *
 * All coroutines started in this view model are linked to the lifecycle. If the view model
 * is destroyed, then all coroutines are cancelled. Likewise, if any of the coroutines encounter
 * an exception, that cancels the other coroutines
 */
abstract class AbstractOdboEditorViewModel<T,KEY>(application: Application) : AndroidViewModel(application) , I_BrowsableEditableData<T> {

    protected val context=application

    lateinit var browsableHelper: I_BrowsableEditableData<T>


    init {
        initViewModel()

        viewModelScope.launch(Dispatchers.IO) {
            browsableHelper = buildBrowsablehelper()
        }
    }

    open fun initViewModel(){}


    abstract fun buildBrowsablehelper():I_BrowsableEditableData<T>

    override fun moveFirst() {
       browsableHelper.moveFirst()
    }

    override fun refreshData() {
        browsableHelper.refreshData()
    }

    override fun moveLast() {
        browsableHelper.moveLast()
    }

    override fun movePrev() {
       browsableHelper.movePrev()
    }

    override fun moveTo(i: Int) {
       browsableHelper.moveTo(i)
    }

    override fun getCurrentElement(): T = browsableHelper.getCurrentElement()

    override fun moveNext() {
        browsableHelper.moveNext()
    }

    override fun updateItem(item:T){
        viewModelScope.launch(Dispatchers.IO) {
            browsableHelper.updateItem(item)
        }
    }

    override fun insertItem(item: T) {
        viewModelScope.launch(Dispatchers.IO) {
            browsableHelper.insertItem(item)
        }
    }

    override fun deleteItem(item: T) {
        viewModelScope.launch(Dispatchers.IO) {
            browsableHelper.deleteItem(item)
        }
    }

    override fun moveToAble(i: Int): Boolean {
       return browsableHelper.moveToAble(i)
    }

    override fun getItemCount(): Int =browsableHelper.getItemCount()

    override fun getCurrentIndex(): Int =browsableHelper.getCurrentIndex()

}